package sqlit3

import (
	"database/sql"
	"fmt"
	_ "github.com/mattn/go-sqlite3"
	"os"
	"time"
)

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

func main() {
	current, _ := os.Getwd()
	db_path := current + "/src/advance/db/sqlit3/foo.db"
	db, err := sql.Open("sqlite3", db_path)
	checkErr(err)

	fmt.Println("######## 插入数据 ######## ")
	//插入数据
	stmt, err := db.Prepare("INSERT INTO userinfo(username, department, created) values(?,?,?)")
	checkErr(err)
	res, err := stmt.Exec("astaxie", "小姐姐", "2012-12-09")
	checkErr(err)
	id, err := res.LastInsertId()
	checkErr(err)
	fmt.Println(id)

	fmt.Println("######## 数据更新 ######## ")
	// 数据更新
	stmt, err = db.Prepare("update userinfo set username=? where uid=?")
	checkErr(err)

	res, err = stmt.Exec("astaxieupdate", id)
	checkErr(err)

	affect, err := res.RowsAffected()
	checkErr(err)

	fmt.Println(affect)

	fmt.Println("######## 查询数据 ######## ")
	// 查询数据
	rows, err := db.Query("SELECT * from userinfo")
	checkErr(err)
	for rows.Next() {
		var uid int
		var username string
		var department string
		var created time.Time
		err = rows.Scan(&uid, &username, &department, &created)
		checkErr(err)
		fmt.Println(uid)
		fmt.Println(username)
		fmt.Println(department)
		fmt.Println(created)
	}
	fmt.Println("######## 删除数据 ######## ")
	// 删除数据
	stmt, err = db.Prepare("delete from userinfo where uid = ?")
	checkErr(err)

	res, err = stmt.Exec(id)
	checkErr(err)

	fmt.Println(affect)

	defer db.Close()

}
